package com.huifaapp.mall.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.ShareFriends;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.ShareUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.openapi.IWXAPI;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;


/**
 * 
* @ClassName: IntroductionPageAdapter 
* @Description: TODO(引导页) 
* @author lijs
* @date 2016年5月11日 下午1:34:37 
*
 */
public class MyLvShareFriendListviewAdapter extends BaseAdapter {
	private Context context;
	private LayoutInflater inflater;
	private List<ShareFriends.DataBean.ListBean>  list;
	private IWXAPI api;
	private static final int SHARET_WXPYQ = 517;
	ArrayList<String> mainImages=new ArrayList<>();
	public MyLvShareFriendListviewAdapter(Context context, List<ShareFriends.DataBean.ListBean> list) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.list=list;

	}

	@Override
	public int getCount() {
		return list == null ? 0 : list.size();
	//Integer.MAX_VALUE;
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public List<ShareFriends.DataBean.ListBean> getList() {
		return list;
	}

	public MyLvShareFriendListviewAdapter setList(List<ShareFriends.DataBean.ListBean> list) {
		this.list = list;
		return this;
	}

	int ds=0;
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (null == convertView) {
			convertView = inflater.inflate(R.layout.mylvsharefriend_item, null);
			holder = new ViewHolder();
			holder.iv_mylvShareFriend_userImage= (ImageView) convertView.findViewById(R.id.iv_mylvShareFriend_userImage);
			holder.tv_mylvShareFriend_name= (TextView) convertView.findViewById(R.id.tv_mylvShareFriend_name);
			holder.tv_mylvShareFriend_timeShop= (TextView) convertView.findViewById(R.id.tv_mylvShareFriend_timeShop);
			holder.gv_mylvShareFriend_ImageGridview= (GridView) convertView.findViewById(R.id.gv_mylvShareFriend_ImageGridview);
			holder.tv_mylvShareFriend_OneButtonSend= (TextView) convertView.findViewById(R.id.tv_mylvShareFriend_OneButtonSend);
			holder.tv_mylvShareFriend_time= (TextView) convertView.findViewById(R.id.tv_mylvShareFriend_time);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		final ShareFriends.DataBean.ListBean bean=list.get(position);
		uploadimageview(holder.iv_mylvShareFriend_userImage,bean.getImg(),null,context);
		holder.tv_mylvShareFriend_name.setText(bean.getTitle());
		holder.tv_mylvShareFriend_timeShop.setText(bean.getWord());
//		Log.e("数据","GridviewUrls=========="+bean.getUrls());
		String[] main=bean.getMainImages().split(",");

		mainImages.clear();
		for (int i=0;i<main.length;i++){

			mainImages.add(main[i]);
			}
		ShareFriendGridViewAdapter adapter=new ShareFriendGridViewAdapter(context,mainImages);
		holder.gv_mylvShareFriend_ImageGridview.setAdapter(adapter);
		holder.tv_mylvShareFriend_OneButtonSend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.e("一键发送","一键发送====="+bean.getMainImages());
				Log.e("分享朋友圈","?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(context)+"&spuIds="+ bean.getSpuIds());
				ApiManager
						.getInstance()
						.getApiServer()
						.getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(context), bean.getSpuIds())
						.compose(ApiManager.<ShareImageBean>handlResult())
						.subscribe(new ObserverCallback<ShareImageBean>(context) {
							@Override
							protected void onSuccessful(ShareImageBean resp) {
								saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXPYQ);
							}

							@Override
							protected void onError(String code, String errMsg) {
								ToastUtils.showShortSafe(errMsg);
							}
						});
			}
		});

		return convertView;
	}


	class ViewHolder {
		private ImageView iv_mylvShareFriend_userImage;
		private TextView tv_mylvShareFriend_name;
		private TextView tv_mylvShareFriend_timeShop;
		private GridView gv_mylvShareFriend_ImageGridview;
		private TextView tv_mylvShareFriend_OneButtonSend;
		private TextView tv_mylvShareFriend_time;

	}
	private void saveImage(List<String> imageUrls, final String cconten, final int type) {

		Log.v("shiran","------------saveImage------------");

		final LoadingDialog dialog = new LoadingDialog(context);
		dialog.setContent("正在生成图片请稍后");


		Observable.just(imageUrls)
				.map(new Function<List<String>, List<String>>() {

					@Override
					public List<String> apply(List<String> list) throws Exception {

						List<String> paths = new ArrayList<String>();
						for (String s : list) {
							FutureTarget<File> future = Glide.with(APP.getInstance())
									.load(s)
									.downloadOnly(500, 500);
							File cacheFile = future.get();
							String uuid = UUID.randomUUID().toString();
							FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
							String pat = savePath + uuid + ".jpg";
							paths.add(pat);

						}


						return paths;
					}
				}).subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<List<String>>() {
					@Override
					public void onSubscribe(Disposable d) {
						if (dialog != null && !dialog.isShowing()) {
							dialog.show();
						}
					}

					@Override
					public void onNext(List<String> value) {
						LogUtils.e(value);
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}

						switch (type) {
							case SHARET_WXPYQ:
								ShareUtils.share9PicsToWXCircle(context, "", value);
								break;
							default:

								break;
						}

					}

					@Override
					public void onError(Throwable e) {
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}
					}

					@Override
					public void onComplete() {
						if (dialog != null && dialog.isShowing()) {
							dialog.dismiss();
							dialog.cancel();
						}
					}
				});

	}
	public static void uploadimageview(final ImageView views, String url, String bili, Context c) {
		DisplayImageOptions HXOptions = new DisplayImageOptions.Builder()
				.cacheInMemory(true)
				.cacheOnDisk(true)
				.considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		ImageLoader.getInstance().displayImage(url, views, HXOptions);
	}

}